package server

import (
	"github.com/FileClassifyWeb/internal/handler"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"path/filepath"
)

type Server struct {
	engine *gin.Engine
}

func NewServer() *Server {
	engine := gin.Default()
	
	var staticDir, templatePattern string
	
	// 获取可执行文件所在目录
	execPath, err := os.Executable()
	if err != nil {
		panic(err)
	}
	execDir := filepath.Dir(execPath)
	
	// 首先尝试从当前目录加载（开发环境）
	if _, err := os.Stat("web/template"); err == nil {
		staticDir = "web/static"
		templatePattern = "web/template/*"
	} else {
		// 如果当前目录没有文件，则从可执行文件目录加载（生产环境）
		staticDir = filepath.Join(execDir, "web/static")
		templatePattern = filepath.Join(execDir, "web/template/*")
	}
	
	// 设置静态文件路由
	engine.Static("/static", staticDir)
	
	// 设置HTML模板路由
	engine.LoadHTMLGlob(templatePattern)
	engine.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", nil)
	})
	
	// 设置WebSocket路由
	engine.GET("/ws", handler.WebSocketHandler)
	
	// 设置API路由
	engine.POST("/classify", handler.ClassifyHandler)
	engine.GET("/select-dir", handler.SelectDirHandler)
	
	return &Server{
		engine: engine,
	}
}

// 实现 http.Handler 接口
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	s.engine.ServeHTTP(w, r)
}

func (s *Server) Run(addr string) error {
	return s.engine.Run(addr)
} 